import {ref, computed, reactive} from 'vue';
import {message} from 'ant-design-vue';
import {delay} from '@/utils/delay';

type TableParam = {
  request: () => any;
  columns: Array<{
    [key: string | number]: any;
  }>;
  config?: {[key: string | number]: any};
  params?: {
    page: number;
    pageSize: number;
    pageSizes: number[];
    total: number;
  };
};
type TableData = {
  data: Array<{[key: string | number]: any}>;
  loading: boolean;
  page: number;
  pageSize: number;
  pageSizes: number[];
  total: number;
};
const defaultParams = {
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50, 100, 200, 500],
  total: 0,
};
export default function useTable({request, columns, config, params = defaultParams}: TableParam) {
  if (!columns) {
    message.error(`请配置表格Table columns 字段 `);
  }
  const tableState = reactive<TableData>({
    data: [], // 数据
    loading: false, // 加载状态
    page: params.page, // 默认第几页
    pageSize: params.pageSize, // 默认每页多少条
    pageSizes: params.pageSizes,
    total: params.total, // 总条数
  });
  // 调用 网络请求 方法处理
  const getTableData = async () => {
    tableState.loading = true;
    try {
      const result = await request();
      const {code, msg, total, rows} = result;
      if (code && code === 200 && !!rows) {
        tableState.data = rows;
        tableState.total = total;
        console.log('tabData网络请求数据：', result);
      }
      await delay(300);
      tableState.loading = false;
    } catch (error) {
      await delay(300);
      tableState.loading = false;
    }
  };
  /**
   * @description 分页
   * @returns
   */
  // 重置网络请求
  const resetTableData = () => {
    tableState.page = params.page;
    tableState.pageSize = params.pageSize;
    getTableData();
  };
  const onChangePage = () => {

  };
  const onChangeSize = () => {};

  const gridOptions = computed(() => {
    const formatColumns = columns?.map((item) => {
      return {
        align: 'center',
        ...item,
      };
    });
    return {
      columns: formatColumns, 
      columnConfig: {
        minWidth: 100,
      },
      height: 'auto',
      headerCellClassName: 'white-header',
      size: 'mini',
      class: 'w-[100%]',
      showOverflow: true,
      seqConfig: {
        seqMethod: (_params: {rowIndex: number}) => {
          const {rowIndex} = _params;
          return rowIndex + 1 + (tableState.page - 1) * tableState.pageSize;
        },
      },
      ...config,
    };
  });

  return {tableState, gridOptions, getTableData, resetTableData};
}
